<template>
  <div class="overview_agent">
    <div class="flex-container">
      <div class="flex-item box-power">
        <ul class="list">
          <li>
            <div class="title" :title="$t('overview.month_generateElectricity')"><i class="iconfont icon-flow" inner></i>{{$t('overview.month_generateElectricity')}}</div>
            <div class="text">
              <span class="value">{{yieldObj.monthYield | numberFloatFrm(true) | getByIndex(0)}}</span>
              <span class="unit">{{yieldObj.monthYield | numberFloatFrm(true) | getByIndex(1)}}</span>
            </div>
          </li>
          <li>
            <div class="title" :title="$t('overview.year_generateElectricity')"><i class="iconfont icon-data" inner></i>{{$t('overview.year_generateElectricity')}}</div>
            <div class="text">
              <span class="value">{{yieldObj.yearYield | numberFloatFrm(true) | getByIndex(0)}}</span>
              <span class="unit">{{yieldObj.yearYield | numberFloatFrm(true) | getByIndex(1)}}</span>
            </div>
          </li>
          <li>
            <div class="title" :title="$t('overview.total_generateElectricity')"><i class="iconfont icon-magic-cube" inner></i>{{$t('overview.total_generateElectricity')}}</div>
            <div class="text">
              <span class="value">{{yieldObj.totalYield | numberFloatFrm(true) | getByIndex(0)}}</span>
              <span class="unit">{{yieldObj.totalYield | numberFloatFrm(true) | getByIndex(1)}}</span>
            </div>
          </li>
        </ul>
      </div>

      <!--发电量统计图-->
      <div class="flex-item box-power-bar" style="flex:1 1 50%;">
        <div class="title">
          {{$t('overview.currentYield')}}
          <ul class="chartBtnWrap">
            <li :class="chartType=='bar'?'active':''" @click="initYieldChart('bar',reportType)"><i class="iconfont icon-chartbar-simple"></i></li>
            <li :class="chartType=='line'?'active':''" @click="initYieldChart('line',reportType)"><i class="iconfont icon-chartline"></i></li>
          </ul>
        </div>
        <div class="btn-group2 right-box-radio clearfix"> 
          <div class="radio-wrap">
            <div :class="reportType==1?'active':''" @click="initYieldChart(chartType,1)">
              <span class="radio-box-modal"></span><font>{{$t('overview.daily')}}</font>：
            </div>
            <div class="btn-group">
              <span class="box-title" :class="{ active:isActive==1 }" @click.stop="toggleBox(1)">
                <span class="title-btn" id="day_menu">{{day}}</span><i class="el-icon-caret-bottom"></i>
              </span>

              <ul class="box-time" style="width:210px">
                <li class="title">{{$t('overview.daily')}}</li>
                <template v-for="count in dayList" >
                    <li :key="count">
                    <el-button 
                      type="text" 
                      :disabled="year==now_year&&month==now_month&&count>now_day" 
                      @click="day=count;isActive=0" 
                    >{{count}}
                    </el-button>
                  </li>
                </template>
              </ul>
            </div>
          </div>

          <div class="radio-wrap">
            <div :class="reportType==2?'active':''" @click="initYieldChart(chartType,2)">
              <span class="radio-box-modal"></span><font>{{$t('overview.month')}}</font>：
            </div>
            <div class="btn-group">
              <span class="box-title" :class="{ active:isActive==2 }" @click.stop="toggleBox(2)">
                <span class="title-btn" id="month_menu">{{month}}</span><i class="el-icon-caret-bottom"></i>
              </span>
              <ul class="box-time" colspan="6"  style="width:180px">
                <li class="title">{{$t('overview.month')}}</li>
                <template v-for="count in 12" >
                  <li :key="count">
                    <el-button 
                      type="text" 
                      :disabled="year==now_year&&count>now_month" 
                      @click="month=count;isActive=0" 
                    >{{count}}
                    </el-button>
                  </li>
                </template>
              </ul>
            </div>
          </div>

          <div class="radio-wrap">
            <div :class="reportType==3?'active':''" @click="initYieldChart(chartType,3)">
              <span class="radio-box-modal"></span><font>{{$t('overview.year')}}</font>：
            </div>
            <div class="btn-group">
              <span class="box-title" :class="{ active:isActive==3 }" @click.stop="toggleBox(3)">
                <span class="title-btn" id="year_menu">{{year}}</span><i class="el-icon-caret-bottom"></i>
              </span>
              <ul class="box-time" style="width:150px">
                <li class="title">{{$t('overview.year')}}</li>
                <template v-for="count in yearList">
                  <li class="grow" :key="count" @click="year=count;isActive=0">
                    <el-button 
                      type="text">
                      {{count}}
                    </el-button>
                  </li>
                </template>
              </ul>
            </div>
          </div>

          <div class="radio-wrap">
            <div :class="reportType==4?'active':''" @click="initYieldChart(chartType,4)"> 
              <span class="radio-box-modal"></span>{{$t('all')}}
            </div>
          </div>
          
        </div>
        <div id="yieldChart" :style="{width: '100%', height: '300px'}"></div>
      </div>

      <div class="flex-item box-info">
        <ul class="list">
          <li class="title">
            {{$t('overview.Information_Statistics')}}
            <i class="iconfont icon-marker-site" style="flex: 1;text-align: right;color: #fd5f5f;font-size: 24px;cursor:pointer" @click="showMap()"></i>
          </li>
          <li>
            <span class="name">{{$t('overview.sumAgent')}}</span>
            <span class="value">{{info.agentCount}}</span>
          </li>
          <li>
            <span class="name">{{$t('overview.sumUser')}}</span>
            <span class="value">{{info.allUser}}</span>
          </li>
          <li>
            <span class="name">{{$t('overview.todayCount')}}</span>
            <span class="value">{{info.todayAlarm}}</span>
          </li>
          <li>
            <span class="name">{{$t('overview.total_inverter')}}</span>
            <span class="value">{{info.total}}</span>
          </li>
          <li>
            <span class="name">{{$t('overview.online_inverter')}}</span>
            <span class="value">{{info.active}}</span>
          </li>
          <li>
            <span class="name">{{$t('overview.total_siteTitle')}}</span>
            <span class="value">{{info.siteNum}}</span>
          </li>
        </ul>
      </div>
    </div>
    <div class="flex-container">
      <div class="flex-item box-sale-bar">
        <div class="title">
          {{$t('saleByAreaAnalysis.saleTotal')}}
          <el-radio-group v-model="dateType" @change="initSaleChart" size="mini" class="pull-right">
            <el-radio-button label="month">{{$t('index_js_days')}}</el-radio-button>
            <el-radio-button label="year">{{$t('overview.month')}}</el-radio-button>
            <el-radio-button label="all">{{$t('overview.year')}}</el-radio-button>
          </el-radio-group>
        </div>
        <div id="saleChart" :style="{width: '100%', height: '300px'}"></div>
      </div>
    </div>
    <baseBaiduMap :mapData='mapData'></baseBaiduMap>
    <baseGoogleMap :mapData='mapData'></baseGoogleMap>
  </div>
</template>

<script>
import '@/utils/index.js'
import baseBaiduMap from '../../components/map/baseBaiduMap'
import baseGoogleMap from '../../components/map/baseGoogleMap'
let echarts = require('echarts/lib/echarts');

export default {
  components:{
    baseBaiduMap,
    baseGoogleMap
  },
  data(){
    return{
      mapData:{
          width:'100%',
          height:'400px',
          zoom:2,
          center:{
              lng:130,
              lat:29
          },
          mapObj:{},//地图对象
          markers:[],//地图上所有的标记
          showType:'count'
      },
      yieldObj:{monthYield:0,yearYield:0,totalYield:0},
      info:{},
      chartType:'bar',
      reportType:'2',
      dateType:'year',
      dateUnit:{month:this.$t('index.unitTimeDay'),year:this.$t('index.unitTimeMonth'),all:this.$t('index.unitTimeYear')},
      currentTime:this.$options.filters['dateFormat'](new Date()),
      day:this.$options.filters['dateFormat'](new Date(),'DD'),
      month:this.$options.filters['dateFormat'](new Date(),'MM'),
      year:this.$options.filters['dateFormat'](new Date(),'YYYY'),
      now_day:this.$options.filters['dateFormat'](new Date(),'DD'),
      now_month:this.$options.filters['dateFormat'](new Date(),'MM'),
      now_year:this.$options.filters['dateFormat'](new Date(),'YYYY'),
      yearList:[],
      isActive:0
    }
  },
  mounted(){
    for(let i=2017;i<=this.year;i++){
      this.yearList.push(i);
    }
    this.getTimeYield();
    this.initAgent();
    this.initYieldChart(this.chartType,this.reportType);
    this.initSaleChart(this.dateType);
    document.addEventListener('click',this.toggleBox);
    this.getMap()
  },
  destroyed(){
    document.removeEventListener('click',this.toggleBox);
  },
  computed: {
    dayList: function () {
      if(this.month==1||this.month==3||this.month==5||this.month==7||this.month==8||this.month==10||this.month==12) return 31;
      if(this.month==4||this.month==6||this.month==9||this.month==11) return 30;
      if(this.month==2&&this.year%4==0) return 29;
      if(this.month==2&&this.year%4!=0) return 28;
    }
  },
  watch:{
    day(){
      this.initYieldChart(this.chartType,this.reportType);
    },
    month(){
      this.day=this.$options.filters['dateFormat'](new Date(),'DD');
      this.initYieldChart(this.chartType,this.reportType);
    },
    year(){
      this.day=this.$options.filters['dateFormat'](new Date(),'DD');
      this.initYieldChart(this.chartType,this.reportType);
    }
  },
  methods:{
    // handleBodyClick: function(){
    //   console.log('body click');
    //   if (this.isActive!=0) {
    //     this.isActive=0;
    //   }
    // },
    toggleBox(index){
      index=index!=0?index:0;
      if(index==0) console.log(index);
      if (this.isActive==index) {
        this.isActive=0;
      }else{
        this.isActive=index;
      }
    },
    forEachYield(res,i,xAxisData,yAxisData,theMax){
      let flag=true;
      res.forEach(item=>{
        if(item.time==i){
          xAxisData.push(item.time);
          if(item.yieldtoday!=null){
            if(item.yieldtoday==0){
              yAxisData.push(theMax);
            }else{
              yAxisData.push(item.yieldtoday.toFixed(2));
            }
          }else{
            yAxisData.push('-');
          }
          flag=false;
        }
      })
      if(flag){
        xAxisData.push(i);
        yAxisData.push('-');
      }
    },
    async getTimeYield(){
      let res=await this.API.getTimeYield({
        currentTime: this.currentTime
      })
      this.yieldObj=res;
    },
    async initAgent(){
      let res = await this.API.getCountParam({
        currentTime: this.currentTime
      })
      this.info=res;
    },
    async initYieldChart(chartType,reportType){
      this.chartType=chartType;
      this.reportType=reportType;
      let res = await this.API.getYield({
        reportType : reportType,
        day : this.day,
        month : this.month,
        year : this.year,
        webTime : this.$options.filters['dateFormat'](new Date(),'YYYY,MM,DD')
      })
      console.log(res);
      let xAxisData=[],yAxisData=[],array_data=[];
      let _this=this;
      let resData=res['returnList'];
      let unit_time='';
      let theMax=0;//最大值
      if(resData){
        resData.forEach(item=>{
          array_data.push(item.yieldtoday);
        })
        theMax=this.$options.filters['MaxNum']((array_data)/10000);
        //根据日期类型初始化数据
        if(reportType==1){
          unit_time=this.$t('index.unitTimeHour');
          let hour=23;
          for(let i=0;i<=hour;i++){
            this.forEachYield(resData,i,xAxisData,yAxisData,theMax);
          }
        }else if(reportType==2){
          unit_time=this.$t('index.unitTimeDay');
          for(let i=1;i<=this.dayList;i++){
            this.forEachYield(resData,i,xAxisData,yAxisData,theMax);
          }
        }else if(reportType==3){
          unit_time=this.$t('index.unitTimeMonth');
          for(let i=1;i<=12;i++){
            this.forEachYield(resData,i,xAxisData,yAxisData,theMax);
          }
        }else if(reportType==4){
          unit_time=this.$t('index.unitTimeYear');
          let temp;
          for(var i=0; i < resData.length; i++){
            xAxisData.push(resData[i].time);
            for(var j=0; j < resData.length-i-1; j++){
              if(resData[j].time>resData[j+1].time){
                temp=resData[j];
                resData[j]=resData[j+1];
                resData[j+1]=temp;
              }
            }
            if(resData[i].yieldtoday!=null){
              if(resData[i].yieldtoday==0){
                yAxisData.push(theMax);
              }else{
                yAxisData.push(resData[i].yieldtoday.toFixed(2));
              }
            }else{
              yAxisData.push('-');
            }

          }
        }
      }
      let yieldChart = echarts.init(document.getElementById('yieldChart'));
      let optionObj={
        tooltip:{
          formatter: function (params) {
              if(params[0]['data']==theMax){
                  return _this.$options.filters['formatUnitTime'](unit_time,params[0]['axisValue'])+'<br>'+params[0]['seriesName']+' : 0.00'+'kWh'
              }else{
                  return _this.$options.filters['formatUnitTime'](unit_time,params[0]['axisValue'])+'<br>'+params[0]['seriesName']+' : '+params[0]['value']+'kWh'
              }
            }
        },
        xAxis:{
          name:'('+unit_time+')',
          data : xAxisData
        },
        yAxis:{
          name:'kWh'
        },
        grid : {
          left : '15px',
          top : '50px',
          right : '70px',
          bottom : '20px',
          containLabel :true
        },
        series : [this.EchartsUtil.getSeries({type:this.chartType,name:this.$t('overview.currentYield'),data:yAxisData})]
      };
      yieldChart.setOption(this.EchartsUtil.getOption(optionObj));
      window.addEventListener('resize', () => {
          yieldChart.resize();
      })
    },
    async initSaleChart(_dateType){
      this.dateType=_dateType;
      let res = await this.API.saleStatisticsByTime({
        timeType: this.dateType,
        currentTime: this.currentTime
      })
      let xAxisData=[],seriesData=[];
      if(res){
        res.forEach(item=>{
          if(this.dateType=='month'){
            xAxisData.push(item.day);
          }else if(this.dateType=='year'){
            xAxisData.push(item.month);
          }else if(this.dateType=='all'){
            xAxisData.push(item.year);
          }
          
          seriesData.push(item.sum);
        })
      }
      
      // 基于准备好的dom，初始化echarts实例
      let saleChart = echarts.init(document.getElementById('saleChart'));
      let unit_time=this.dateUnit[this.dateType];
      let stand=this.$t('stand')
      let optionObj={
        tooltip:{
          formatter: function (params) {
            return params[0]['axisValue']+'('+unit_time+') : '+params[0]['value']+stand
          }
        },
        xAxis:{
          data : xAxisData
        },
        yAxis:{
          name:this.$t('stand')
        },
        grid :{
          left : '20px',
          top : '45px',
          right : '25px',
          bottom : '20px',
          containLabel :true
        },
        series : [this.EchartsUtil.getSeries({type:'bar',data:seriesData})]
      };
      saleChart.setOption(this.EchartsUtil.getOption(optionObj));
      window.addEventListener('resize', () => {
          saleChart.resize();
      })
    },
    async getMap(){
      this.UtilsFun.createGoogle()
      let res = await this.API.getRoundSiteAddress()
      // console.log(res,'------点')
      res.forEach(item=>{
        let pointType=localStorage.getItem('mapType')==1?'baidu':'google'
        var transParam = this.UtilsFun.transformPoint(item.latitude,item.longitude,pointType);
        this.mapData.markers.push({
          lng:Number(transParam.longitude),
          lat:Number(transParam.latitude),
          name:item.nation,
          count:item.siteCount
        })
      })
      this.mapData.center=this.mapData.markers[0]
      console.log(this.mapData.markers)

    },
    //打开地图
    showMap(){
      // console.log(this.mapData.markers,'----------------------point')
      if(this.mapData.markers.length>0){
        if(localStorage.getItem('mapType')==1){
          this.$store.commit('setVisibleBaiduMap',true)
        }else{
          this.$store.commit('setVisibleGoogleMap',true)
        }
      }else{
        // this.$message.error('您未录入电站位置信息')
      }
    }
  }
}
</script>

<style lang="less">
@media screen and (max-width: 1560px) {
  body{
    .overview_agent .flex-container{
      #yieldChart {
        height: 250px !important;
      }
      #saleChart {
        height: 250px !important;
      }
      .flex-item{
        margin: 5px !important;
        .title{
          padding: 5px !important;
          .text-overflow()
        }
        .list li:not(:first-child) {
            padding: 6px 0 !important;
        }
      }
      .flex-item.box-info .list li .name {
        font-size: 14px;
      }
    }
  }
}
@color_box_bg:#EFEFEF;
@color_title:#444;
@color_text:#636162;
@color_unit:#636162;
@color_light:#ff8920;
@border_bottom:1px dashed #D1D1D1;
@border_radius:3px;
@color_unit:#8a8a8a;

.text-overflow(){
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.overview_agent{
  .flex-container{
    display:-webkit-flex;
    display: flex;

    .flex-item{
      margin: 10px;
      flex:1 1 25%;
      background:@color_box_bg;
      border-radius: @border_radius;
      .title{
        padding: 10px;
        border-bottom: @border_bottom;
        color: @color_title;
      }
      &.box-power{
        background: transparent;
        flex:1 1 15%;
        min-width: 150px;
        .list{
          display: flex;
          flex-direction: column;
          align-content:space-between;
          height: 100%;
          li{
            display: flex;
            flex-direction: column;
            flex: 1;
            background:@color_box_bg;
            border-radius: @border_radius;
            &:not(:last-child){
              margin-bottom: 10px;
            }
            .title{
              color: @color_title;
              border-bottom: @border_bottom;
              padding: 6px;
            }
            .text{
              padding: 15px 0;
              text-align: center;
              .value{
                font-size: 20px;
                color: @color_light;  
              }
              .unit{
                font-size: 12px;
                color: @color_unit;
                margin-left:3px ;
              }
            }
          }
        }
      }
      &.box-power-bar{
        position: relative;
        min-width: 415px;
        .chartBtnWrap{
          float: right;
          li{
            float: left;
            padding-left: 15px;
            cursor: pointer;
            .iconfont{
              font-size: 20px;
              color: @color_unit;
            }
            &.active{
              .iconfont{
                color:@color_light;
              }
            }
          }
        }
        .right-box-radio{
          position: absolute;
          right: 20px;
          z-index: 3;
        }
      }
      &.box-info{
        .list{
          padding: 0 10px;
          display: flex;
          flex-direction: column;
          align-content:space-between;
          height: 100%;
          li{
            display: flex;
            flex:1;
            align-items: center;
            &.title{
              padding: 0;
              height: 40px;
              line-height: 40px;
              color: @color_title;
            }
            &:not(:first-child){
              padding: 10px 0;
            }
            &:not(:last-child){
              border-bottom: @border_bottom;
            }
            .name{
              flex:1;
              font-size: 16px;
              color:@color_text;
              padding-right: 10px;
              .text-overflow()
            }
            .value{
              float: right;
              font-size: 18px;
              color:@color_light;
            }
          }
        }
      }
      .el-button--primary {
        color: #6d6d6d;
        background-color: #ffffff;
        border-color: #f4b600;
      }
    }

  }
}
</style>